package com.google.code.alpaca.example.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.Extent;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import com.google.code.alpaca.example.model.Message;

public class MessageRepository {

	private static PersistenceManagerFactory pmfInstance;

	/**
	 * @see example.model.Messages#getAll()
	 */
	public List<Message> getAll() {
		PersistenceManager pm = getPmfInstance().getPersistenceManager();
		try {
			List<Message> messages = new ArrayList<Message>();
			Extent<Message> extent = pm.getExtent(Message.class, false);
			for (Message message : extent) {
				messages.add(message);
			}
			extent.closeAll();

			return messages;
		} finally {
			pm.close();
		}
	}

	/**
	 * @see example.model.Messages#create(example.model.Message)
	 */
	public void create(Message message) {
		PersistenceManager pm = getPmfInstance().getPersistenceManager();
		try {
			pm.makePersistent(message);
		} finally {
			pm.close();
		}
	}

	/**
	 * @see example.model.Messages#deleteById(java.lang.Long)
	 */
	public void deleteById(Long id) {
		PersistenceManager pm = getPmfInstance().getPersistenceManager();
		try {
			pm.deletePersistent(pm.getObjectById(Message.class, id));
		} finally {
			pm.close();
		}
	}

	private static PersistenceManagerFactory getPmfInstance() {
		if (pmfInstance == null)
			pmfInstance = JDOHelper
					.getPersistenceManagerFactory("transactions-optional");
		return pmfInstance;
	}
}
